import { ref, computed, onMounted, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { getPublicScripts } from '/@/api/blog/scripts';
import { useGlobalLoading } from '/@/hooks/blog/useGlobalLoading';

export function useBlogScripts() {
  const router = useRouter();
  const pageRef = ref<HTMLElement>();
  const showEasterEgg = ref(false);
  const searchQuery = ref('');
  const currentPage = ref(1);
  const pageSize = ref(6);

  // 使用全局加载状态
  const { withLoading } = useGlobalLoading();

  // 脚本数据
  const scripts = ref([]);
  const totalScripts = ref(0);

  // 获取脚本数据
  const fetchScripts = async () => {
    return withLoading(async () => {
      const params: any = {
        pageNo: currentPage.value,
        pageSize: pageSize.value,
      };

      // 如果有搜索关键词
      if (searchQuery.value.trim()) {
        params.name = searchQuery.value.trim();
      }

      console.log('🔍 请求脚本数据，参数:', params);
      const res = await getPublicScripts(params);
      console.log('📦 脚本API响应:', res);

      if (res) {
        scripts.value = res.records || [];
        totalScripts.value = res.total || 0;
        console.log('✅ 脚本数据更新成功，数量:', scripts.value.length);
      } else {
        console.error('❌ 脚本API请求失败:', res);
      }
    });
  };

  // 计算属性
  const paginatedScripts = computed(() => {
    return scripts.value;
  });

  // 方法
  const handleKeydown = (event: KeyboardEvent) => {
    console.log('🔤 键盘事件触发:', event.key, event.target);

    if (event.key === 'ArrowLeft') {
      console.log('⬅️ 检测到左箭头键，准备返回');
      event.preventDefault();
      event.stopPropagation();
      goBack();
    }
  };

  const goBack = () => {
    console.log('🔄 执行返回操作');
    try {
      if (window.history.length > 1) {
        router.go(-1);
      } else {
        router.push('/');
      }
    } catch (error) {
      console.error('❌ 返回失败:', error);
      try {
        router.back();
      } catch (backError) {
        console.error('❌ router.back()也失败:', backError);
        router.push('/');
      }
    }
  };

  const handleSearch = () => {
    currentPage.value = 1;
    fetchScripts();
  };

  const viewScript = (script: any) => {
    // 跳转到脚本详情页
    console.log('查看脚本:', script.name);
    router.push(`/blog/scripts/${script.id}`);
  };

  const handlePageChange = (page: number) => {
    currentPage.value = page;
    fetchScripts();
    // 滚动到页面顶部
    if (pageRef.value) {
      pageRef.value.scrollIntoView({ behavior: 'smooth' });
    }
  };

  // 初始化
  onMounted(() => {
    fetchScripts();

    // 设置页面焦点
    nextTick(() => {
      if (pageRef.value) {
        pageRef.value.focus();
      }
    });
  });

  return {
    pageRef,
    showEasterEgg,
    searchQuery,
    currentPage,
    pageSize,
    paginatedScripts,
    totalScripts,
    handleKeydown,
    goBack,
    handleSearch,
    viewScript,
    handlePageChange,
  };
}
